package com.godenwater.web.listener;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.monitor.FileAlterationListener;
import org.apache.commons.io.monitor.FileAlterationObserver;

import com.godenwater.recv.decode.YanyuMessageDecoder;
import com.godenwater.recv.model.CommonMessage;
import com.godenwater.recv.server.all.RtuConfig;
import com.godenwater.recv.service.MessageYyConsumer;
import com.godenwater.utils.ByteUtils;

public class MsgYYFileListener implements FileAlterationListener {

    MsgFileMonitor monitor = null;
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");

    @Override
    public void onStart(FileAlterationObserver observer) {
        // System.out.println("onStart");
    }

    @Override
    public void onDirectoryCreate(File directory) {
        System.out.println("onDirectoryCreate:" + directory.getName());
    }

    @Override
    public void onDirectoryChange(File directory) {
        System.out.println("onDirectoryChange:" + directory.getName());
    }

    @Override
    public void onDirectoryDelete(File directory) {
        System.out.println("onDirectoryDelete:" + directory.getName());
    }

    @Override
    public void onFileCreate(File file) {
        handleFile(file);
        handleOtherFile(file.getParentFile());
    }

    /**
     * 处理其他未处理的文件
     *
     * @param parentFile
     */
    private void handleOtherFile(File parentFile) {
        File files[] = parentFile.listFiles();
        for (File file : files) {
            handleFile(file);
        }
    }

    /**
     * 处理文件
     *
     * @param file
     */
    public void handleFile(File file) {
        if (!file.exists()) {
            return;
        }
        System.out.println("YY file create:" + file.getName());
        // FileUtils.copyFileToDirectory(srcFile, destDir);
        String fileName = file.getName();
        String[] fileInfo = fileName.split("_");
        // 第一步：读取报文文件
        List<String> lines;
        try {
            String channel = fileInfo[0];
            //String stcd = fileInfo[1];
            //String crcflag = fileInfo[2];
            // lines = Files.readAllLines(Paths.get("/tmp/test.csv"),
            // Charset.forName("UTF-8"));
            lines = FileUtils.readLines(file, "UTF-8");
            for (String line : lines) {
                System.out.println("READ YY>> " + line);
                // 1.1：转换为报文字节数组
                byte[] bytes = ByteUtils.hexStringToBytes(line);
              if (line.length()<49){
                  System.out.println("READ YY>>报文长度不够残缺 ，丢弃！");
                  FileUtils.deleteQuietly(file);
                  return;
              }else {
              String time = line.substring(10,20);//时间是BCD码，不会存在FFFFFF
              String eot = line.substring(line.length()-6,line.length()-4);//获取结束符
                if(line.startsWith("7E")&&(eot.equals("03")||eot.equals("17"))&&!time.contains("FF")) {
						CommonMessage message = YanyuMessageDecoder.decode(bytes);
						MessageYyConsumer consumer = new MessageYyConsumer();
						consumer.process(channel, message, "0", "", 0);
                }else {
                	 System.out.println("READ YY>>报文不满足7e开头，以03或17为结束符 ，报文时间不是BCD码 ，丢弃！");
                     FileUtils.deleteQuietly(file);
                     return;
                }
                }
                
            }
            // 最后，将文件拷贝至成功目录
            String rcvpath = RtuConfig.getMsgRcvPath();
            FileUtils.copyFileToDirectory(file, new File(rcvpath + "/YY/suc/" + sdf.format(new Date())),
                    true);
            // 然后清除目录文件
            FileUtils.deleteQuietly(file);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.out.println("READ YY>>报文不满足7e开头，以03或17为结束符 ，报文时间不是BCD码 ，丢弃！");
            FileUtils.deleteQuietly(file);
            return;
        }
    }

    @Override
    public void onFileChange(File file) {
        System.out.println("onFileChange:" + file.getName());
    }

    @Override
    public void onFileDelete(File file) {
        System.out.println("onFileDelete:" + file.getName());
    }

    @Override
    public void onStop(FileAlterationObserver observer) {
        // System.out.println("onStop");
    }

}
